package chapter10.section4;

//程序10-3 按照Java数据类型进行输入和输出的数据流
import java.io.*;
import java.util.Random;

public class DataInOutDemo {
	// 输出10个整数到指定的文件
	public static void dataOut(String fileName) throws IOException {
		FileOutputStream fos = new FileOutputStream(fileName);
		DataOutputStream dos = new DataOutputStream(fos);
		Random rand = new Random();
		for (int i = 0; i < 10; i++) {
			int x = rand.nextInt(10000);
			dos.writeInt(x);
		}
		dos.close();
	}

	// 从指定的文件中读取整数
	public static void dataIn(String fileName) throws IOException {
		FileInputStream fis = new FileInputStream(fileName);
		DataInputStream dis = new DataInputStream(fis);
		System.out.print("从文件中读取了:");
		while (true) {
			try {
				int x = dis.readInt();// 从文件读一个整数
				System.out.printf("%d\t", x);
			} catch (EOFException e) {// 到达文件尾
				break;// 退出循环
			}
		}
		dis.close();
	}

	public static void main(String[] args) {
		try {
			dataOut("test.dat");
			dataIn("test.dat");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}